package com.ivan.message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.ivan.beans.Message;

public class MessagesPool {

	private static final Map<Long, Message> msgPool = new ConcurrentHashMap<Long, Message>();
	
	private static Object lock = new Object();
	
	public static void pushMessage(Message message){
		synchronized(lock){
			msgPool.put(System.currentTimeMillis(), message);
		}
	}
	
	public static Map<Long, List<Message>> getMessageByDate(Long datePos){
		List<Message> history = new ArrayList<Message>();
		UserService userService = UserServiceFactory.getUserService();
		User user =	userService.getCurrentUser();
		Long latestPos = null;;
		if(user != null){
			String fromUser = user.getEmail();
			synchronized(lock){
				Set<Long> keys = msgPool.keySet();
				for(Long key : keys){
					if(key > datePos){
						Message msg = msgPool.get(key);
						if(fromUser.equalsIgnoreCase(msg.getFromUser()) ||
								fromUser.equalsIgnoreCase(msg.getToUser())){
							history.add(msg);
							latestPos = key;
						}
					}
				}
			}
		}
		Map<Long, List<Message>> result = new HashMap<Long, List<Message>>();
		result.put(latestPos, history);
		return result;
	}
	
	public static String generateTextForClient(List<Message> history){
		StringBuffer sb = new StringBuffer();
		UserService userService = UserServiceFactory.getUserService();
		User user =	userService.getCurrentUser();
		for(Message msg : history){
			if(user != null){
				String fromUser = user.getEmail();
				if(fromUser.equalsIgnoreCase(msg.getFromUser())){
					sb.append("<div class='from-user-msg' >");
				} else {
					sb.append("<div class='to-user-msg' >");
				}
			}
			sb.append(msg.getFromUser())
				.append(" ")
				.append(msg.getMsgDate())
				.append("<br/>")
				.append(msg.getMessage())
				.append("<br/>")
				.append("</div>");
		}
		String result = sb.toString();
		result = result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
		return result;
	}
	
}
